<template>
  <div class="daily-article">
    <div class="daily-article-title">{{ data.title }}</div>
    <div class="daily-article-content" v-html="data.body"></div>
    <div class="daily-comments" v-show="comments.length"></div>
    <span>评论（{{ comments.length }}）</span>
    <div class="daily-comment" v-for="comment in comments" :key="comment.id">
      <div class="daily-comment-avatar">
        <img :src="comment.avatar" />
      </div>
      <div class="daily-comment-content">
        <div class="daily-comment-name">{{ comment.author }}</div>
        <div class="daily-comment-time" v-time="comment.time"></div>
        <div class="daily-comment-text">{{ comment.content }}</div>
      </div>
    </div>
  </div>
</template>
<script>
import Time from './../time.js'
import $ from './../../libs/util.js'
export default {
  directives: { Time },
  props: {
    id: {
      type: Number,
      default: 0
    }
  },
  data () {
    return {
      data: {},
      comments: []
    }
  },
  methods: {
    getArticle () {
      $.ajax.get('news/' + this.id).then(res => {
        // 替换图片地址为自己接口里的地址
        res.body = res.body
          .replace(/src="http/g, 'src="' + $.imgpath + 'http')
        res.body = res.body
          .replace(/src="https/g, 'src="' + $.imgpath + 'https')
        this.data = res
        // 返回文章顶部。不然会停留在上一篇文章底部的位置
        window.scrollTo(0, 0)
        this.getComments()
      })
    },
    getComments () {
      this.comments = []
      $.ajax.get('story/' + this.id + '/short-comments').then(res => {
        this.comments = res.comments.map(comment => {
          // 将头像的图片地址转为代理地址
          comment.avatar = $.imgpath + comment.avatar
          return comment
        })
      })
    }
  },
  watch: {
    id (val) {
      if (val) this.getArticle()
    }
  }
}
</script>
